﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using CE.User;
using CE.Global;

public partial class user_reset_password : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        Culture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null)
        {
        }

        if (!Page.IsPostBack)
        {
            txtNewPassword.Attributes.Add("onblur", "ShowValidationEffect('" + txtNewPassword.ClientID + "','" + rfvNewPassword.ClientID + "');");
            txtRetypeNewPassword.Attributes.Add("onblur", "ShowValidationEffect('" + txtRetypeNewPassword.ClientID + "','" + rfvRetypeNewPassword.ClientID + "');");
            
            Session["UMMSG"] = null;
            Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);
            string rq_authkey = HttpUtility.ParseQueryString(theRealURL.Query).Get("authkey");
            string rq_uid = HttpUtility.ParseQueryString(theRealURL.Query).Get("uid");
            if (rq_authkey != string.Empty && rq_uid != string.Empty)
            {
                if (rq_authkey.Length > 0 && rq_uid.Length > 0)
                {
                    if (!isMobileBrowser())
                    {
                        ViewState["AutoKey"] = rq_authkey;
                        ViewState["UID"] = rq_uid;
                        Account _account = new Account();
                        AccountDB _accountdb = new AccountDB();
                        _account = _accountdb.GetUserAccountByAuthKey(rq_authkey, rq_uid);
                        if (_account != null)
                        {
                            txtNewPassword.Enabled = true;
                            txtRetypeNewPassword.Enabled = true;
                            btnSubmit.Enabled = true;
                        }
                        else
                        {
                            lblMessage.Text = Resources.ErrorMessage.InvalidUserId;
                            txtNewPassword.Enabled = false;
                            txtRetypeNewPassword.Enabled = false;
                            btnSubmit.Enabled = false;
                        }
                    }
                    else
                    {
                        Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
                        string domainUrl = "";
                        int portUrl = myUri.Port;
                        domainUrl = "http://" + myUri.Host + ((portUrl.ToString() == "80") ? "" : ":" + portUrl.ToString()) + "/mobile/resetpassword.aspx?authkey=" + Request.Params["authkey"] + "&uid=" + Request.Params["uid"];

                        Response.Redirect(domainUrl);
                    }
                }
                else
                {
                    lblMessage.Text = Resources.ErrorMessage.InvalidUserId;
                    txtNewPassword.Enabled = false;
                    txtRetypeNewPassword.Enabled = false;
                    btnSubmit.Enabled = false;
                }
            }
            else
            {
                lblMessage.Text = Resources.ErrorMessage.PleaseryAgain;
                txtNewPassword.Enabled = false;
                txtRetypeNewPassword.Enabled = false;
                btnSubmit.Enabled = false;
            }
        }
    }

    public static bool isMobileBrowser()
    {
        //GETS THE CURRENT USER CONTEXT
        HttpContext context = HttpContext.Current;

        //FIRST TRY BUILT IN ASP.NT CHECK
        if (context.Request.Browser.IsMobileDevice)
        {
            return true;
        }
        //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
        if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
        {
            return true;
        }
        //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
        if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
            context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
        {
            return true;
        }
        //AND FINALLY CHECK THE HTTP_USER_AGENT 
        //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
        if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
        {
            //Create a list of all mobile types
            string[] mobiles =
                new[]
                {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone"
                };

            //Loop through each item in the list created above 
            //and check if the header contains that text
            foreach (string s in mobiles)
            {
                if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
                {
                    return true;
                }
            }
        }

        return false;
    }
       
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("resetpassword");
            Page.Validate("resetpassword");
            if (Page.IsValid)
            {
                if (ViewState["AutoKey"] != null && ViewState["UID"] != null)
                {
                    AccountDB _accountdb = new AccountDB();
                    if (_accountdb.ResetPassword(txtNewPassword.Text, ViewState["AutoKey"].ToString(), ViewState["UID"].ToString()))
                    {
                        string _redirectUrl = CE.Global.General.GetUrl("/user/user-message", Page);
                        Session["UMMSG"] = "UMG,1992";
                        Response.Redirect(_redirectUrl);
                    }
                    else
                    {
                        lblMessage.Text = Resources.ErrorMessage.ResetPasswordFaild;
                    }
                }
                else
                {
                    lblMessage.Text = Resources.ErrorMessage.InvalidKey;
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtNewPassword.Text = HttpUtility.HtmlEncode(txtNewPassword.Text);
        txtRetypeNewPassword.Text = HttpUtility.HtmlEncode(txtRetypeNewPassword.Text);

        //NewPassword
        if (rfvNewPassword.Enabled && rfvNewPassword.ValidationGroup == strValidationGroup)
        {
            rfvNewPassword.Validate();
            if (rfvNewPassword.IsValid == false)
            {
                txtNewPassword.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtNewPassword.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtNewPassword.ControlStyle.CssClass = "input-fields";
        }

        //Feed back
        if (rfvRetypeNewPassword.Enabled && rfvRetypeNewPassword.ValidationGroup == strValidationGroup)
        {
            rfvRetypeNewPassword.Validate();
            if (rfvRetypeNewPassword.IsValid == false)
            {
                txtRetypeNewPassword.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtRetypeNewPassword.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtRetypeNewPassword.ControlStyle.CssClass = "input-fields";
        }

    }

}

